<template>
  <div>
    <div class="amap-page-container">
      <!-- <el-amap-search-box v-if="!mapPoint" class="search-box" :search-option="searchOption" :on-search-result="onSearchResult" /> -->
      <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult" />
      <el-amap ref="map" vid="amapDemo" :center="center" :zoom="zoom" class="amap-demo" :events="events" :plugin="plugin">
        <!-- <el-amap-marker v-if="!mapPoint" vid="component-marker" :position="[lng, lat]" /> -->
        <el-amap-marker vid="component-marker" :position="[lng, lat]" />
        <el-amap-polygon v-for="(polygon, index) in polygons" v-if="mapPoint" :ref="`polygon_${index}`" :editable="true" :vid="index" :path="polygon.path" :draggable="polygon.draggable" :events="polygon.events" :fillColor="polygon.fillColor" />
      </el-amap>
      <div class="toolbar">
        <span v-if="!loaded">正在定位,如长时间无反应,请刷新</span>
        <div v-else style="font-size: 12px;">
          地址: {{ addressData.formattedAddress }}
        </div>
        <div v-if="mapPoint">
          <el-link :underline="false" type="primary" @click="reselectMap()">点击清空</el-link>
          <el-link :underline="false" type="primary" style="margin-left: 5px;" @click="recoveryMap()">点击恢复</el-link>
          <el-link
            v-show="this.polygons[0].path.length > this.initMapPoint.length"
            :underline="false"
            type="primary"
            style="margin-left: 5px;"
            @click="returnMap()"
          >撤回标点
          </el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { AMapManager } from 'vue-amap'
export default {
  props: {
    setcenter: {
      type: Array,
      default: () => []
    },
    mapPoint: { // 用于判断是否为围栏
      type: Boolean,
      default: false
    },
    initMapPoint: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const self = this
    return {
      searchOption: {
        city: '莆田',
        citylimit: false
      },
      zoom: 12,
      center: [25.439092, 119.031851],
      addressData: {},
      polygons: [ // 围栏
        {
          draggable: false,
          fillColor: new String('rgba(255,255,0,0.2)'),
          path: [],
          events: {
            click: () => {
              // console.log(AMapManager.getComponent(0))
              console.log(this.$refs.map.$$getCenter())
              console.log(this.$refs.polygon_0[0].$$getPath())
            }
          }
        }
      ],
      loaded: false,
      isInitCenter: true, // 判断是否初始化到当前定位
      plugin: [{ // / 默认定位在自己所在区域
        pName: 'Geolocation',
        events: {
          init(o) {
            if (self.isInitCenter) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  self.lng = result.position.lng
                  self.lat = result.position.lat
                  self.center = [self.lng, self.lat]
                  self.loaded = true
                  var geocoder = new window.AMap.Geocoder({
                    radius: 1000,
                    extensions: 'all'
                  })
                  geocoder.getAddress([self.lng, self.lat], function(status, result) { // 第一次进来获取位置
                    if (status === 'complete' && result.info === 'OK') {
                      if (result && result.regeocode) {
                        self.addressData = result.regeocode
                        self.getMark('initPosition')
                        self.$nextTick()
                      }
                    }
                  })
                  self.$nextTick()
                }
              })
            }
          }
        }
      }],
      events: { // 点击得到经纬度
        click(e) {
          const { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat

          // 这里通过高德 SDK 完成。
          var geocoder = new window.AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.addressData = result.regeocode
                self.getMark()
                self.$nextTick()
              }
            }
          })
        }
      },
      /* markers: [ // 点击添加标记
        {
          events: {
            click: () => {
              alert('click marker')
            },
            dragend: (e) => {
              console.log('---event---: dragend')
              this.markers[0].position = [e.lnglat.lng, e.lnglat.lat]
            }
          },
          visible: true,
          draggable: false,
          template: '<span>1</span>'
        }
      ], */
      lng: 0,
      lat: 0
    }
  },
  mounted() {
    this.initCenterFn()
    this.initMapPointFn()
  },
  created() {
  },
  methods: {
    initCenterFn() { // 初始化中心点
      if (this.setcenter.length !== 0) { // 如果有传入经纬度则重置目前经纬度为传入的经纬度
        this.isInitCenter = false // 不根据所在位置定位
        this.center[0] = this.setcenter[0] // 根据经纬度确定中心点
        this.center[1] = this.setcenter[1]
        this.lng = this.setcenter[0] // 赋值传入的经纬度
        this.lat = this.setcenter[1]
        this.loaded = true

        var geocoder = new window.AMap.Geocoder({ // 获取详细地址
          radius: 1000,
          extensions: 'all'
        })
        geocoder.getAddress(this.center, (status, result) => {
          console.log(this.center)
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.regeocode) {
              this.addressData = result.regeocode
              this.getMark()
              this.$nextTick()
            }
          }
        })
      }
    },
    initMapPointFn() { // 初始化围栏
      if (this.initMapPoint.length !== 0) {
        this.isInitCenter = false // 不根据所在位置定位
        this.loaded = true
        const arr = []
        let lngSum = 0 // 计算经纬度总和
        let latSum = 0
        this.initMapPoint.forEach(item => {
          lngSum = lngSum + item.lng
          latSum = latSum + item.lat
          arr.push([item.lng, item.lat])
        })
        this.center[0] = lngSum / (this.initMapPoint.length) // 计算出平均的经纬度
        this.center[1] = latSum / (this.initMapPoint.length)
        this.polygons[0].path = arr
      }
    },
    getMark(e) { // 获取点击的位置的信息
      if (!this.mapPoint) { // 如果不是围栏则直接获取位置信息
        this.$emit('getMap', this.lng, this.lat, this.addressData)
      } else { // 点击添加围栏
        if (!e) { // 第一次进来的时候不保存
          this.polygons[0].path.push([this.lng, this.lat])
        }
      }
    },
    getMapPoint() { // 供外界调用,保存围栏
      const mapPoint = []
      this.$refs.polygon_0[0].$$getPath().forEach(item => {
        const obj = {
          lng: item[0],
          lat: item[1]
        }
        mapPoint.push(obj)
      })
      return mapPoint
    },
    reselectMap() {
      this.polygons[0].path = []
    },
    recoveryMap() {
      this.initMapPointFn()
      this.center = [this.center[0], this.center[1]]
    },
    returnMap() {
      if (this.polygons[0].path.length > this.initMapPoint.length) {
        this.polygons[0].path.pop()
      }
    },
    onSearchResult(pois) {
      if (pois.length > 0) {
        console.log(pois[0].lng, pois[0].lat)
        this.markers = [pois[0].lng, pois[0].lat]

        const center = {
          lng: pois[0].lng,
          lat: pois[0].lat
        }

        var geocoder = new AMap.Geocoder({ // 获取详细地址
          radius: 1000,
          extensions: 'all'
        })
        geocoder.getAddress([center.lng, center.lat], (status, result) => { // 修改位置address
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.regeocode) {
              this.addressData = result.regeocode
              this.getMark()
              this.$nextTick()
            }
          }
        })
        this.center = [center.lng, center.lat] // 修改地图中心点
        this.lng = center.lng // 修改标记位置
        this.lat = center.lat
      }
    }
  }
}
</script>

<style scoped lang="scss">
       .amap-demo {
            height: 35vw;
          }

          .search-box {
            position: absolute;
            top: 25px;
            right: 20px;
          }

          .amap-page-container {
            position: relative;
          }
          .toolbar{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 5px;
          }
</style>
